var json2xml = null;
$(document).ready(function (){
	require([
		'jtopo',
		index_web_app_name+'js/plugin/topo/node-ui.js',
		index_web_app_name+'js/plugin/topo/topoToolLable.js',
		'Json2xml',
		'drag',
		'topoCustomNode',
		'topoCustomLink',
		'topoCustomFoldLink',
		'topoCustomFlexionalLink',
		'topoCustomTextNode',
		'topoCustomContainer',
		'topoCustomNephogram',
		'topoCustomNephogramPublic',
		'asset',
		'abPanel',
		'css!'+index_web_app_name+'css/topo.css'] ,function (
			jtopo,
			nodeFactory,
			toolsLable,
			Json2xml,
			drag,
			CustomNode,
			CustomLink,
			CustomFoldLink,
			CustomFlexionalLink,
			CustomTextNode,
			CustomContainer,
			CustomNephogram,
			customNephogramPublic,
			asset,
			abPanel){
			var lineNumber = 0;

	var appSystem = "appSystem";	

	$("#content_div").css("padding" ,"0");
	$("#pg-content").css("padding" ,"0");
	$(".pg-content-div").css('padding','0');
	
	json2xml = new Json2xml({
			attributePrefix : ""
	});
	nodeFactory.init();
	var nodeFunction = nodeFactory._nodeFunction;
	
	nodeFunction.getNodeEntry().cloudNumber = 0;

	var this_params = index_query_param_get();
	
	var initEvent=function(event)
	{

		$('.toggle-btn').click(function(){
			$('.topo-editor').toggleClass('shrink-left')
			$(this).toggleClass('active')
			_canvas_resize(document.getElementById('canvasDraw'))
		})
		function _canvas_resize(canvas){
			var height = $(canvas).parent().height()
			var width = $(canvas).parent().width()
			$(canvas).height(height).width(width)
			canvas.height = height
			canvas.width = width
		}
		$('#other_btn').click(function (){
			$('.other-menu').toggleClass('active')
		})

		drag.customDrag($("#tool_heading"),$('#tool_div'));
		$("#closeCanvasDrawShowAttrLineDiv").click(function(){
			$("#canvasDrawShowAttr").hide();
		});
		$("#canvasDrawShowAttr").hide();
		
		$("#exportJSONData").click(function(){
			$('.other-menu').toggleClass('active')
			nodeFunction.exportJSONData();
		});
		$("#emptyScene").click(function(){
			$('.other-menu').toggleClass('active')
			nodeFunction.emptyScene("清空画板区？");
		});
		$("#stageSelectMode").click(function(){
			nodeFunction.changeSceneModel('select');
		});
		$("#backToFirstIn").click(function(){
			nodeFunction.backToFirstIn();
		});
		$("#headingOne").click(function (){
			$("#tool_div").toggleClass("topo-min-heading");
		});
		$("[name='modifyFunction']").each(function(){
		    $(this).click(function(){
		    	nodeFunction.modifyFunction($(this).attr("value"));
		    });
		  });
		$("#reSetMessage").click(function(){
			$('.other-menu').toggleClass('active')
			getTopoInfo({});
		});

		$("#createcloud").click(function(){
			var scene = nodeFunction.getScene();
			var nodes = scene.selectedElements;
			for(var i=0;i<nodes.length;i++){
				if(nodes[i].type != "netNode"){
					nodes.remove(i);
					i--;
				}
			}
			if(nodes == null || nodes.length <=0)
				g_dialog.operateAlert(null,"未选中任何节点","error");
			else 
				createcloud(nodes);
		});

		$("[data-id=query]").click(function(){
			nodeFunction.queryNode(nodeFunction.getNodeEntry().scene,selectFunc);
			function selectFunc(saveObj){
				var scene = nodeFunction.getNodeEntry().scene;
				var nodes = scene.getAllNodes();
				scene.cancleAllSelected();
				for(var i=0;i<nodes.length;i++){
					var node = nodes[i];
					if(node.name.indexOf(saveObj.name) != -1 || (node.asset&&node.asset.name&&node.asset.name.indexOf(saveObj.name) != -1) || (node.asset&&node.asset.ip&&node.asset.ip.indexOf(saveObj.name) != -1) ){
						node.selected = true;
						scene.addToSelected(node);
					}
				}
			}
		});

		$("[data-id=clearState]").click(function(){
			nodeFunction.clearState(nodeFunction.getNodeEntry().scene);
		});

		$("[data-id=setBgi]").click(function (){
			um_ajax_get({
				url : "module/monitor_config/topo_manage_detail_tpl.html",
				server : index_web_app_name,
				successCallBack : function (data){

					var checkedImg;

					g_dialog.dialog($(data).find("#changeBackground"),{
						title : '设置背景图片',
						width:"750px",
						init : init,
						initAfter:initAfter,
						saveclick:save_click,
						autoHeight : true
					});
					function init(el){

					}
					function initAfter(el){
						$.ajax({
							url : index_web_app + index_soc_prefix + 'topoManage/getImagePath',
							type : 'get',
							xhrFields: {
								withCredentials: true
							},
							success : function (data){
								var files = data.data;
								if(!!files){
									var fileList = files.split(',');
									for(var i=0;i<fileList.length;i++){
										var filePath = fileList[i];
										var img = $('<img src="'+(index_web_app + index_soc_prefix + filePath)+'" width="200px" data-path="'+filePath+'" style="margin:10px;border: 1px solid black;box-shadow: 10px 10px 5px #888888;"/>'); 
										var div = $('<div style="position: relative;display: inline-block;vertical-align: middle;"></div>');
										div.append(img);
										var removeBtn = $('<div style="position: absolute;right:20px;bottom: 20px;"><i class="icon-remove" style="color:red;font-size:24px;"></i></div>');
										div.append(removeBtn);
										removeBtn.click(function (e){
											var that = this;
											var delImagePath = $(this).siblings('img').attr('data-path');
											$.ajax({
												url : index_web_app + index_soc_prefix + 'topoManage/deleteImage',
												data : {delImagePath:delImagePath},
												type : 'get',
												dataType : 'json',
												async : true,
												timeout : 6000,
												xhrFields: {
													withCredentials: true
												},success : function (data){
													if(data.flag){
														g_dialog.operateAlert(el,'删除成功','info');
														$(that).parent().remove();
													}else {
														g_dialog.operateAlert(el,data.msg,'error');
													}
												},
												error : function (e)
												{
												}
											});
										});
										img.click(function (e){
											checkedImg = $(this).attr('data-path');
											$(this).parent().append('<div class="checkedImg"><i class="icon-check-sign" style="color:green;font-size:24px;opacity:1;"></i></div>');
											$(this).parent().siblings().find('.checkedImg').remove();
											el.find('.radio').removeClass('disabled');
											el.find('[name=bgi_type]').removeAttr('disabled');
										})
										el.find('#bgi-list').append(div);
									}
								}
								el.find('#defaultBGI').click(function(e){
									checkedImg = "";
									$(this).parent().append('<div class="checkedImg"><i class="icon-check-sign" style="color:green;font-size:24px;opacity:1;"></i></div>');
									$(this).parent().siblings().find('.checkedImg').remove();
									el.find('[name=bgi_type][value=1]').prop('checked',true);
									el.find('[name=bgi_type][value=0]').prop('checked',false);
									el.find('[name=bgi_type]').trigger('change');
									el.find('[name=bgi_type]').attr('disabled','disabled');
									el.find('.radio').addClass('disabled');
								});
								$.ajax({
									url : index_web_app + index_soc_prefix + 'topoManage/getTopoInfo',
									data : {topoId:this_params.topoId,regionId:this_params.regionId},
									type : 'post',
									dataType : 'json',
									async : true,
									timeout : 6000,
									xhrFields: {
										withCredentials: true
									},
									success : function (data){
										var bgi = data.topoBackground;
										if(!bgi.split(',')[0]){
											el.find('[name=bgi_type][value=1]').prop('checked',true);
											el.find('[name=bgi_type][value=0]').prop('checked',false);
											el.find('[name=bgi_type]').trigger('change');
											el.find('#defaultBGI').click();
										}else {
											var bgis = bgi.split(',');
											if(bgis.length>1){
												el.find('[name=bgi_type][value=1]').prop('checked',true);
												el.find('[name=bgi_type][value=0]').prop('checked',false);
												el.find('[name=bgi_type]').trigger('change');
											}else {
												el.find('[name=bgi_type][value=0]').prop('checked',true);
												el.find('[name=bgi_type][value=1]').prop('checked',false);
												el.find('[name=bgi_type]').trigger('change');
											}
											el.find('[data-path="'+bgis[0]+'"]').click();
										}
									},
									error : function (e)
									{
									}
								});
							}
						});
					}
					function save_click(el,saveObj){
						if(checkedImg == undefined || checkedImg == null){
							g_dialog.operateAlert(el,'请选择想要设置的背景图片','error');
							return ;
						}
						if(el.find('[name=bgi_type]:checked').val() == '1'){
							checkedImg += ',repeat';
						}
						$.ajax({
							type : 'get',
							url : index_web_app + index_soc_prefix + 'topoManage/changeImage',
							data : {topoId : this_params.topoId ,backgroundName : checkedImg},
							xhrFields: {
								withCredentials: true
							},
							success : function (data){
								if(data.flag){
									g_dialog.operateAlert(null,'设置成功','info');
									g_dialog.hide(el);
									setBackgroundImage(checkedImg);
								}else {
									g_dialog.operateAlert(el,data.msg,'error');
								}
							}
						});
					}
				}
			})
		});

		$('[data-id=bgi]').click(function (){
			$.ajax({
				tyle : "GET",
				url : "module/monitor_config/topo_manage_detail_tpl.html",
				success : function (data){
					g_dialog.dialog($(data).find("#backgroundInfo"),{
						title : '上传背景图片',
						width : "630px",
						init : init,
						initAfter : initAfter,
						saveclick : save_click
					});
					function init(el){
						g_validate.init(el);

						index_create_upload_el(el.find("#bgi"));
					}
					function initAfter(el){
					}
					function save_click(el,saveObj){
						var v = g_validate.fileSuffixLimit(el.find("#bgi").val() ,"png,jpg,bmp" ,true ,false);
						if (!v.flag) 
						{
							g_validate.setError(el.find("#ptMap") ,v.msg);
							return false;
						}
						if (!g_validate.validate(el)){
							return false;
						}
						var form = el.find("[id=upload_bgi_form]");
						um_ajax_file(form ,{
							url : 'topoManage/uploadFile',
							paramObj: saveObj,
							maskObj : el.closest("[data-id*=umDialog]"),
							successCallBack : function (data){
								g_dialog.hide(el);
								g_dialog.operateAlert();
							}
						});
					}
				}
			});
		});
	}
	
	$('#canvasTool').slimscroll({
		allowPageScroll : true
	});
	
	//重新定义formatObjectToXml函数实现,由于和应用监控保存的结构迥异需要自己重新定义转换实现
	nodeFunction.formatObjectToXml = function(scene){
		try{
			var nodeStr='',nodeStr2='',linkStr='',linkStr2='',foldLinkStr = '',squarelyflexionalLinkStr='',textStr='',containerStr='';

			var str = '<root x="'+scene.translateX+'" y="'+scene.translateY+'">';
			
			var childs = [];
			for(var i=0;i<scene.childs.length;i++){
				
			}
			nodeNum = 0;
			createNodeSecDomainList();
			str += '<nodes>';
			
			//优先处理云，有还原操作
			var nephogramStr = customNephogramPublic.toXml(scene).nephogramStr;
			for(var i=0;i<scene.childs.length;i++){
				var child = scene.childs[i];
				if(child instanceof CustomNode){
					nodeNum++;
					if(child.type == appSystem)
					{
						nodeStr2 += toAppSystemXml(child);
					}
					else
					{
						nodeStr += child.serialize();
						nodeSecDomainList.push(child.asset.securityDomainId);
					}
				}else if(child instanceof CustomLink){
					if(child.isMylink){
						linkStr2 += nodeFunction.getLinkXmlFromLinkNode(child,"myline");
					}
					else{
						linkStr += child.serialize();
					}
						
				}else if(child instanceof CustomFoldLink){
					foldLinkStr += child.serialize();
				}else if(child instanceof CustomTextNode){
					textStr += child.serialize();
				}else if(child instanceof CustomContainer){
					containerStr += child.serialize();
				}else if(child instanceof CustomFlexionalLink){
					squarelyflexionalLinkStr += child.serialize();
				}
			}
			str += nodeStr;
			str += '</nodes>';
			
			str += '<mynodes>';
			str += nodeStr2;
			str += '</mynodes>';

			str += '<lines>';
			str += linkStr;
			str += foldLinkStr;
			str += squarelyflexionalLinkStr;
			str += '</lines>';
			
			str += '<mylines>';
			str += linkStr2;
			str += '</mylines>';

			str += '<nephograms>';
			str += nephogramStr;
			str += '</nephograms>';

			str += '<dynTexts>';
			//str += textStr;
			str += nodeFunction.getTextNodeXml(nodeFunction.getNodeEntry().scene,"dynText");
			str += '</dynTexts>';

			str += '<squareBoxes>';
			str += containerStr;
			str += nodeFactory._group.toXml2(nodeFunction.getNodeEntry().scene);
			str += '</squareBoxes>';

			str += '</root>';

			return str;
		}catch(e){
			console.log(e);
		}
	}
	function toAppSystemXml(node){
		return '<appSystem><id>'+node.id+'</id><name>'+node.text+'</name><x>'+node.x+'</x><y>'+node.y+'</y></appSystem>';
	}
	var nodeNum = 0;
	var nodeSecDomainList=null;

	function createNodeSecDomainList(){
		nodeSecDomainList = new Array();
		nodeSecDomainList.filter(function (item){
			if(nodeSecDomainList.indexOf(item) != -1){
				return false;
			}else return true;
		});
	}
	nodeFunction.selfPost = function(xmldateStr){
		var pObj = this;

		var mainCanvas = document.getElementById('canvasDraw');
		var imageData = mainCanvas.toDataURL('image/png');
		var json = {
				topoId : this_params.topoId,
				topoXML : xmldateStr,
				amount : nodeNum,
				defaultShow : this_params.defaultShow?this_params.defaultShow:0,
				secIdFilteredArr : nodeSecDomainList.join(),
				currTheme : this_params.themePath,
				DeltaInfoFlag : 0,
				regionId : this_params.regionId,
				imageData : imageData
			};
		nodeNum = 0;
		nodeSecDomainList = null;
		$.ajax({
			url : index_web_app + index_soc_prefix + 'topoManage/addTopoDetailNew',
			data : json,
			type : 'post',
			dataType : 'json',
			async : false,
			timeout : 3000,
			xhrFields: {
				withCredentials: true
			},
			success : function (data){
				if(!data.flag){//保存未成功
					g_dialog.operateAlert(null,data.msg,"error");
					nodeFunction.emptyScene();
					nodeFunction.formatQueryData(xmldateStr);
					return false;
				}
				g_dialog.operateAlert(null,"保存成功！","info");
				nodeFunction.emptyScene();
               	initData();
			},
			error : function (e){
				g_dialog.waitingAlertHide();
				if(e.statusText == "timeout")
				{
					g_dialog.operateAlert(null,"响应超时!","error");
				}
				nodeFunction.emptyScene();
				nodeFunction.formatQueryData(xmldateStr);
			}
		});
	}
	function getTopoInfo(obj){
		$.ajax({
			type : "GET",
			url : "module/monitor_config/topo_manage_detail_tpl.html",
			success : function (data){
				g_dialog.dialog(
					$(data).find("[id=topoinfo]"),
					{
						width:"500px",
						title:"拓扑信息",
						init:init,
						saveclick:save_click,
						autoHeight: true
					}
				);
				function init(el){
					$.ajax({
						url : index_web_app + index_soc_prefix + 'topoManage/getTopoInfo',//topoManage/addTopoDetailNew
						data : {topoId:this_params.topoId,regionId:this_params.regionId},
						type : 'post',
						dataType : 'json',
						async : true,
						timeout : 6000,
						xhrFields: {
							withCredentials: true
						},
						success : function (data){
							var length = 0;
							var clouds = nodeFunction.getScene().findElements(function (a){
								return a.type == "cloudNode";
							});
							var assetMass = new Array();
							for(var i=0;i<clouds.length;i++){
								length += clouds[i]._nodes.length;
								for(var j=0;j<clouds[i]._nodes.length;j++){
									put2Arry(assetMass,clouds[i]._nodes[j]);
								}
							}
							var netNodes = nodeFunction.getScene().findElements(function (a){
								return a.type == "netNode";
							});
							for(var j=0;j<netNodes.length;j++){
								put2Arry(assetMass,netNodes[j]);
							}
							
							g_grid.render($("#monitorList"),{
								header:[
									{text:'设备类型',name:"type"},
									{text:'设备数量',name:"num"}
								],
								data:assetMass,
								hideSearch : true,
								allowCheckBox : false
							});

							length += netNodes.length;
							$(el).find("label[data-id='assetNum']").text(length);
							$(el).find("label[data-id='topoName']").text(data.topoName);
							$(el).find("label[data-id='creDate']").text(data.creDate);
							$(el).find("label[data-id='creUser']").text(data.creUser);
							!data.showStatus && (data.showStatus = 0);
							this_params.defaultShow = data.showStatus;
							$(el).find(":radio[name='defaultShow'][value='" + this_params.defaultShow + "']").prop("checked", "checked");
						},
						error : function (e)
						{
							console.log(e);
						}
					});
				}
				function put2Arry(assetMass,node){
					var k = 0;
					for(;k<assetMass.length;k++){
						if(assetMass[k].type == node.asset.type){
							break;
						}
					}
					if( k >=  assetMass.length){
						assetMass[k] = {};
						assetMass[k].type = node.asset.type;
						assetMass[k].num = 1;
					}
					else
					{
						assetMass[k].num = Number(assetMass[k].num)+1; 
					}
				}
				function save_click(el,saveObj){
					this_params.defaultShow = saveObj.defaultShow;
					nodeFunction.exportJSONData();
					g_dialog.hide(el);
				}
			}
		});

	}
	var json2xml2 = new Json2xml({});
	nodeFunction.formatQueryData = function(data){
		var jsonobj2 = this.xmlToJsonObj(data);
		console.log(jsonobj2)
		nodeFunction.getNodeEntry().tmpXmlObj = jsonobj2;
		nodeFunction.getNodeEntry().rootObj = jsonobj2;
		this.doinitPanelData(nodeFunction.getNodeEntry().rootObj);
	}
	nodeFunction.xmlToJsonObj = function(xmldateStr){
		return json2xml2.xml_str2json(xmldateStr).root;
	}
	nodeFunction.doinitPanelData = function(jsonobj){
		if(jsonobj){
			var stage = nodeFunction.getNodeEntry().stage;
			stage.id=jsonobj.id;
	    	_root = jsonobj;
	    	var scene = nodeFunction.getNodeEntry().scene;
	    	stage.add(scene);
	    	!_root._x && (_root._x = scene.translateX);
	    	!_root._y && (_root._y = scene.translateY);
	    	scene.translateX = Number(_root._x);
	    	scene.translateY = Number(_root._y);
	    	//添加节点
	    	if(_root.nodes && _root.nodes.node){	
	    		_root.nodes.node = nodeFunction.objToArray(_root.nodes.node);
		    	for(var i=0;i<_root.nodes.node.length;i++){
		    		var item = _root.nodes.node[i];
		    		var node = new CustomNode(item);
		    		node.type = "netNode";
		    		nodeFunction.getNodeEvent().addEventForNode(node);
		    		scene.add(node);
		    	}
	    	}
	    	//应用节点
	    	if(_root.mynodes && _root.mynodes.appSystem){	
	    		_root.mynodes.appSystem = nodeFunction.objToArray(_root.mynodes.appSystem);
		    	for(var i=0;i<_root.mynodes.appSystem.length;i++){
		    		var item = _root.mynodes.appSystem[i];
		    		item.edId = item.id;
		    		item.assetName = item.name;
		    		item.ptMap = "/img/draw/appSystem.svg";
		    		item = customItem(item,0,scene);
		    		var node = new CustomNode(item);
		    		node.type = appSystem;
		    		node.setImage("/img/draw/appSystem.svg");
		    		nodeFunction.getNodeEvent().addEventForNode(node);
		    		scene.add(node);
		    	}
	    	}
	    	//添加连线
	    	if(_root.lines && _root.lines.line){
	    		_root.lines.line = nodeFunction.objToArray(_root.lines.line);
		    	for(var i=0;i<_root.lines.line.length;i++)
		    	{
		    		var dependence = _root.lines.line[i];
		    		if(dependence._id.split("::").length >= 3){
		    			dependence.id = dependence._id;
		    		}
		    		else{
			    		dependence.id = dependence.networkLink.startId+"::"+dependence.networkLink.endId+"::"+lineNumber;
						dependence._id = dependence.id;
		    		}
		    		lineNumber = lineNumber+1;
		    		
		    		dependence._startId = dependence.networkLink.startId;
		    		dependence._endId = dependence.networkLink.endId;
		    		var link = null;
		    		try{
		    			if(dependence._type === "line"){
		    				link = new CustomLink(dependence,scene);
		    			}else if(dependence._type === "foldline"){
		    				link = new CustomFoldLink(dependence,scene);
		    			}else if(dependence._type === "squarelyflexionalline"){
		    				link = new CustomFlexionalLink(dependence,scene);
		    			}else {
		    				link = new CustomLink(dependence,scene);
		    			}
		    		}catch(e){
		    			continue;
		    		}
		    		
		    		link.id = dependence.id;
		    		link.type = "dependence";
		    		//固定颜色,如果没有修改
		    		// link.strokeColor = "0,200,255";
		    		try{
		    			var startNode = nodeFunction.findNodeByScene(scene,dependence.networkLink.startId);
		    			//将数据存储起来
		    			nodeFunction.putModifyStyle(startNode,{
		    				lineColor:dependence.extend.strokeColor,
		    				lineSize:dependence.extend.lineWidth,
		    				lineAlpha:dependence.extend.alpha,
		    				endId:dependence.networkLink.endId},true);
		    		}catch(e){
		    		}
		    		nodeFunction.getNodeEvent().linkDbClick(link);
		    		scene.add(link);
		    	}
	    	}
	    	//创建云节点
	    	if(_root.nephograms && _root.nephograms.nephogram){	
	    		_root.nephograms.nephogram = nodeFunction.objToArray(_root.nephograms.nephogram);
		    	for(var i=0;i<_root.nephograms.nephogram.length;i++){
		    		customNephogramPublic.formatCloudByCloudObj(scene,_root.nephograms.nephogram[i]);
		    		nodeFunction.getNodeEntry().cloudNumber = nodeFunction.getNodeEntry().cloudNumber+1;
		    	}
	    	}
	    	//新连线
	    	if(_root.mylines && _root.mylines.myline){
	    		_root.mylines.myline = nodeFunction.objToArray(_root.mylines.myline);
		    	for(var i=0;i<_root.mylines.myline.length;i++){
		    		var dependence = _root.mylines.myline[i];
					dependence._id = dependence.id;
					var ids = dependence.id.split("::");
					dependence.networkLink = {};
					dependence.networkLink.startId = ids[0];
					dependence.networkLink.endId = ids[1];
		    		dependence._startId = dependence.networkLink.startId;
		    		dependence._endId = dependence.networkLink.endId;
		    		var link = new CustomLink(dependence,scene);
		    		link.id = dependence.id;
		    		link.type = "dependence";
		    		link.isMylink = true;
		    		try{
		    			var startNode = nodeFunction.findNodeByScene(scene,ids[0]);
		    			//将数据存储起来
		    			nodeFunction.putModifyStyle(startNode,{
		    				lineColor:dependence.lineColor,
		    				lineSize:dependence.lineSize,
		    				lineAlpha:dependence.lineAlpha,
		    				endId:ids[1]},true);
		    			link.text = dependence.lineText;
		    			link.lineWidth = dependence.lineSize;
		    			link.strokeColor = dependence.lineColor;
		    			link.alpha = dependence.lineAlpha;
		    		}catch(e){
		    		}
		    		nodeFunction.getNodeEvent().linkDbClick(link);
		    		scene.add(link);
		    	}
	    	}
	    	//添加动态文本
	    	if(_root.dynTexts && _root.dynTexts.dynText){
	    		_root.dynTexts.dynText = nodeFunction.objToArray(_root.dynTexts.dynText);
	    		for(var i=0;i<_root.dynTexts.dynText.length;i++){
		    		var textObj = _root.dynTexts.dynText[i];
		    		var textNode = new CustomTextNode(textObj);
		    		textNode.type = "text";
		    		scene.add(textNode);
		    		nodeFunction.getNodeEvent().addEventForNode(textNode);
		    	}
	    	}
	    	//添加分组
	    	if(_root.squareBoxes && _root.squareBoxes.squareBox){
	    		_root.squareBoxes.squareBox = nodeFunction.objToArray(_root.squareBoxes.squareBox);
	    		for(var i=0;i<_root.squareBoxes.squareBox.length;i++){
		    		var containerObj = _root.squareBoxes.squareBox[i];
		    		var containerNode = new CustomContainer(containerObj);
		    		scene.add(containerNode);

		    		var childs = scene.childs;
		    		childs.forEach(function (child){
		    			if(child instanceof CustomNode || child instanceof CustomTextNode){
		    				if(containerNode.isInBound(child.x,child.y)){
		    					containerNode.add(child);
		    				}
		    			}
		    		});
		    	}
	    	}
			//最新分组
	    	if(_root.squareBoxes && _root.squareBoxes.container)
	    		nodeFactory._group.appendAllNodeToContainer(scene,nodeFactory._group.getContainerArray(_root.squareBoxes.container));
		}else {
			g_dialog.operateAlert(null,"数据加载出错","error");
		}
	}
	//初始化工具栏
	nodeFunction.initSceneTools("canvasTool");
	//初始化画图区
	nodeFunction.initScene("canvasDraw");

	initBgi();
	$("#canvasDraw").oneTime(1000,function() {
		this.width = $(this).parent().width();
		this.height = $(this).parent().height();
	});
	//初始化操作框
	nodeFunction.initOperatingBox("canvasDrawShowAttr");
	//初始化线段操作框
	nodeFunction.initOperatingBoxForLine("canvasDrawShowAttrLine");
	//初始化分组器设置框
	nodeFactory._group.initOperatingBoxForGroup("modifyGroupStlye");
	//设置节点连线的颜色
	nodeFunction.setLinkLineColor("255,0,0");
	//设置监控器列表请求地址
	nodeFunction.setQueryMonitorUrl("appMonitor/queryConfigXml?1=1");
	//设置监控器状态请求地址
	nodeFunction.setQueryOneMonitorStatusUrl("appMonitor/queryAppCompStatus");
	//设置通过监控器ID获取监控器属性的请求地址
	nodeFunction.setQueryOneMonitorStatusByIdUrl("/monitorView/queryMonitorInfoByMonitorId");
	//设置获取后台xml模板URL 
	nodeFunction.setXmlModuleUrl("topoManage/getTopo?1=1");
	//设置保存XML URL地址
	nodeFunction.setSaveDataUrl("topoManage/addTopoDetailNew?1=1");
	//设置工具栏图片路径
	nodeFunction.setImgePath("/img/draw/");
	//设置挂载监控器图片路径
	nodeFunction.setCustomMonitorImgePath("/img/custommonitor/new/",'.svg');
	//设置是否是编辑状态
	nodeFunction.isEditerJob();
	//设置是否在编辑时显示设置的监控器图标,如果需要就调用此函数即可
	nodeFunction.isShowMonitorImgInEdit();
	//设置新增应用跳转函数
//	nodeFunction.setAddAppFunction(nodeFunction.addAppFunction);
	var appId = this_params.topoId?this_params.topoId:undefined;
//	//初始化XML结构必须先初始化XML结构
//	nodeFunction.initXmlModuleData();
	var fromType = this_params.fromType?this_params.fromType:'thumb';
	if(fromType == "addApp" || appId == undefined)
	{
		nodeFunction.isAddApp(window.location.href);
		//如果是新增界面需要隐藏修改按钮
		$("#reSetMessage").hide();
	}
	
	/**
	 * 重新定义node节点事件
	 */
	nodeFactory.customComEvent(
			{
				type:"line",
				line:{click:null,mouseup:linkRightClick}//定义线段事件处理函数
			});
	nodeFactory.customComEvent(
			{
				type:"layer",
				line:{click:null,mouseup:linkRightClick}//定义虚线事件处理函数
			});
	nodeFactory.customComEvent(
			{
				type:"arrow",
				line:{click:null,mouseup:linkRightClick}//定义箭头事件处理函数
			});
	nodeFactory.customComEvent(
			{
				type:"dependence",
				line:{click:null,mouseup:linkRightClick,dbclick:loadNetPorts}//定义箭头事件处理函数
			});
	
	function loadNetPorts(obj){
		
		var _ids = obj.node.id.split("::");
		var start = nodeFunction.findNodeByScene(nodeFunction.getNodeEntry().scene,_ids[0]);
		var end = nodeFunction.findNodeByScene(nodeFunction.getNodeEntry().scene,_ids[1]);
		if(		appSystem == start.type || 
				appSystem == end.type	||
				"cloudNode" == end.type	||
				"cloudNode" == start.type
				)
			return;
		$.ajax({
			type : "GET",
			url : "module/monitor_config/topo_manage_detail_tpl.html",
			success : function (data){
				g_dialog.dialog(
					$(data).find("[id=asset_netmes]"),
					{
						width:"320px",
						title:"属性配置",
						init:init,
						saveclick:save_click
					}
				);
				function init(el){
					//找出起始点和终点
					var ids = obj.node.id.split("::");
					var start = nodeFunction.findNodeByScene(nodeFunction.getNodeEntry().scene,ids[0]);
					var end = nodeFunction.findNodeByScene(nodeFunction.getNodeEntry().scene,ids[1]);
					$(el).find("#task_start_div label").text(start.name);
					$(el).find("#task_end_div label").text(end.name);
					var startSelect = $(el).find("#task_start_div_val").find('select');
					var endSelect = $(el).find("#task_end_div_val").find('select');
					$(el).find('#speed').val(obj.node.text);
					if(start.asset.ports.port){
						var ports = nodeFunction.objToArray(start.asset.ports.port);
						for(var i=0;i<ports.length;i++){
							var temp = ports[i];
							var option = $('<option value="'+temp._id+'">'+temp._name+'</option>');
							if(temp._id==obj.node.lineObj.networkLink.startPort){
								option.prop('selected',true);
							}
							startSelect.append(option);
						}
					}
					if(end.asset.ports.port){
						var ports = nodeFunction.objToArray(end.asset.ports.port);
						for(var i=0;i<ports.length;i++){
							var temp = ports[i];
							var option = $('<option value="'+temp._id+'">'+temp._name+'</option>');
							if(temp._id==obj.node.lineObj.networkLink.endPort){
								option.prop('selected',true);
							}
							endSelect.append(option);
						}
					}
					startSelect.select2({
						width : '100%'
					});
					endSelect.select2({
						width : '100%'
					});
				}
				function save_click(el,saveObj){
					obj.node.lineObj.networkLink.startPort = $(el).find("#task_start_div_val").find('select').val();
					obj.node.lineObj.networkLink.endPort = $(el).find("#task_end_div_val").find('select').val();
					obj.node.text = $(el).find('#speed').val();
					obj.node.reloadPort();
					g_dialog.hide(el);
				}
			}
		});
	}
	customNephogramPublic.loadNetPorts = loadNetPorts;
	function tip(obj){
		g_dialog.operateConfirm("请实现类型 ' "+obj.node.type+"' 的操作界面，提供的参数中可拿到全部画布数据，如：画布ID '" +obj.nodeFactory._nodeFunction.getNodeEntry().canDrawId+"',scene,stage.\r\n 全局对象 ：obj.nodeFactory._nodeFunction.getNodeEntry();\r\n主要操作入口：obj.nodeFactory._nodeFunction;\r\n分组入口：obj.nodeFactory._group",{saveclick : function (){
			$(this).remove();
		}});
	}
	function closeRightEvent(){
		g_dialog.operateAlert(null,"请双击修改属性","error");
	}
	function createTextNode(obj){
		nodeFunction.getNodeEntry().linkNode = false;
		var isupdate = false;
		$.ajax({
			type : "GET",
			url : "module/monitor_config/app_monitor_config_detail_tpl.html",
			success : function (data){
				g_dialog.dialog(
					$(data).find("[id=addTextNode]"),
					{
						width:"580px",
						title:"创建/修改文字节点",
						init:init,
						saveclick:save_click
					}
				);
				function init(el){
					if(checkIsNULL(obj.node.text) == false){
						$(el).find("input[data-id='name']").val(obj.node.text);
					}
					if(checkIsNULL(obj.node.fontSize) == false){
						obj.node.fontSize = obj.node.fontSize+"";//
						$(el).find("select[data-id='textsize']").val(obj.node.fontSize.replace("px","").replace("bold ",""));
					}
					if(checkIsNULL(obj.node.fontColor) == false){
						isupdate = true;
						$(el).find("input[data-id='textcolor']").val(obj.node.fontColor);
					}
					if(!checkIsNULL(obj.umIsUpdate)&&obj.umIsUpdate)
						isupdate=true;
					else
						isupdate=false;
					var hex = ("RGB("+obj.node.fontColor+")").colorHex();
					$(el).find("#textcoloriframe").attr("src",nodeFunction.getNodeEntry().colorStagePath+"?color="+hex);
				}
				function save_click(el,saveObj){
					var tempnode = nodeFunction.copyNode(obj.node);
					if(isupdate == false){
						tempnode.x = 200-nodeFunction.getNodeEntry().scene.translateX;
						tempnode.y = 200-nodeFunction.getNodeEntry().scene.translateY;
					}
					else{
						tempnode.x = obj.node.x;
						tempnode.y = obj.node.y;
					}
					if(checkIsNULL(saveObj.name) == true)
						saveObj.name = " ";
					tempnode.name = saveObj.name;
					tempnode.fontSize = saveObj.textsize;
					var input_color = $(window.frames["textcoloriframe"].document).find(".sp-input-container,.sp-cf").find(".sp-input");
					$(el).find("input[data-id='textcolor']").val(input_color.val().colorRgb());
					tempnode.fontColor = input_color.val().colorRgb();
					//
					var textObj = {};
					textObj._x = tempnode.x;
					textObj._y = tempnode.y;
					textObj._width = tempnode.width;
					textObj._height = tempnode.height;
					textObj._id = tempnode.id;
					textObj._text = tempnode.name;
					textObj._color = tempnode.fontColor;
					textObj._fontSize = tempnode.fontSize;
					textObj._fontFamily = tempnode.fontFamily;
		    		var textNode = new CustomTextNode(textObj);
		    		textNode.type = "text";
		    		textNode.font = "bold "+textNode.fontSize + "px " + textNode.fontFamily;
		    		nodeFunction.getNodeEvent().addEventForNode(textNode);

					if(isupdate == true){
						nodeFunction.getNodeEntry().scene.remove(obj.node);
					}
					nodeFunction.getNodeEntry().scene.add(textNode);

					$(el).find("input[data-id='textcolor']").val("");
					g_dialog.hide(el);
				}
			}
		});
	}
	function createAppSystem(obj){
		$.ajax({
			type : "GET",
			url : "module/monitor_config/topo_manage_detail_tpl.html",
			success : function (data){
				g_dialog.dialog(
					$(data).find("[id=appSystemList]"),
					{
						width:"400px",
						title:"添加应用系统",
						init:init,
						saveclick:save_click
					}
				);

				function init(el){
					el.find("button[data-id='save']").remove();
					um_ajax_get({
						url : "appMonitor/queryConfigXml?&compType="+appSystem,
						isLoad : false,
						successCallBack : function (data){
							
							while(data.indexOf("\\")!=-1){
								data = data.replace("\\","");
							}
							var jsonObj = json2xml.xml_str2json(data).root.item;
							nodeFunction.getNodeEntry().appSystems = jsonObj;
							var scene = nodeFunction.getNodeEntry().scene;
							for(var i=0;i<jsonObj.length;i++){
								if(nodeFunction.findNodeBySceneAndType(scene,jsonObj[i].id,appSystem) != null)
									continue;
								var tr = nodeFunction.createMonitorTr(jsonObj[i],appSystem);
								tr.hover(function(){
									$(this).css("background-color","rgb(220,220,220)");
								},function(){
									$(this).css("background-color","");
								});
								tr.dblclick(function(){
									var mid = $(this).attr("id");
									for(var j=0;j<nodeFunction.getNodeEntry().appSystems.length;j++){
										var mObj = nodeFunction.getNodeEntry().appSystems[j];
										if(mid == mObj.id){
											var obj = {};
											obj.edId = mObj.id;
											obj.assetName = mObj.name;
											obj.ptMap = "/img/draw/appSystem.svg";
											var item = customItem(obj,0,scene);
											var node = new CustomNode(item);
								    		node.type = appSystem;
								    		nodeFunction.getNodeEvent().addEventForNode(node);
								    		node.setImage(obj.ptMap);
								    		scene.add(node);
								    		$(this).remove();
											break;
										}
									}
								});
								el.find("#select_monitor1").append(tr);
							}
						}
						});
				}
				function save_click(el,saveObj){
					g_dialog.hide(el);
				}
			}
		});
	}
	function createLink(obj){
		
		var select = $("#"+nodeFunction.getNodeEntry().canvasToolBarId).find("div[compType='"+obj.node.type+"']").attr("clicktime");
		if(select == undefined)
		{
			nodeFunction.getNodeEntry().linkNode = true;
			//$("#flashContent").find("#canvasDraw").css("cursor","url('/img/cur/concur.cur')");
		}
		else
		{
			nodeFunction.getNodeEntry().linkNode = undefined;
			//$("#flashContent").find("#canvasDraw").css("cursor","");
		}
	}
	function createAssetNode(obj){
		nodeFunction.getNodeEntry().linkNode = false;
		asset.queryDialog({
	 		saveclick : filterCallback
	 	});
	}
	var index_list_col_header = [
								  {text:'设备名称',name:"assetName",render:function (text,data){
										
								  	return '<a href="javascript:void(0)">'+text+'</a>';
								  }
								  },
								  {text	:'管控域',name:"securityDomainName"},
								  // {text : '业务域',name : "bussinessDomainName"},
								  {text : 'IP',name : 'mainIp'},
								];
	function filterCallback(saveObj,el){
		//获取已在画布内的资源ID
		var scene = nodeFunction.getNodeEntry().scene;
		var deviceStr = "";
		var nodeIds = new Array();
		for(var i=0;i<scene.childs.length;i++){
			var child = scene.childs[i];
			if(child instanceof CustomNode){
				nodeIds.push(child.id);
				deviceStr+=(child.id+",");
			}else if(child instanceof CustomNephogram){
				child._nodes.map(function (item){
					nodeIds.push(item.id);
					deviceStr+=(item.id+",");
				})
			}
		}
		
		if(saveObj.securityDomain) saveObj.securityDomainId = saveObj.securityDomain;
		if(saveObj.bussinessDomain) saveObj.bussinessSystemId = saveObj.bussinessDomain;
		if(saveObj.assetType) saveObj.assetTypeId = saveObj.assetType;
		if(saveObj.ipRadioStatus) saveObj.mainIpType = saveObj.ipRadioStatus;
		if(saveObj.ipRadioStatusStartIp) saveObj.startIp = saveObj.ipRadioStatusStartIp;
		if(saveObj.ipRadioStatusEndIp) saveObj.endIp = saveObj.ipRadioStatusEndIp;
		if(saveObj.ipRadioStatusIpv6) saveObj.mainIp = saveObj.ipRadioStatusIpv6;

		$.ajax({
			type : "GET",
			url : "module/monitor_config/topo_manage_detail_tpl.html",
			success : function (data){
				g_dialog.dialog(
					$(data).find("[id=assetList]"),
					{
						width:"680px",
						title:"添加资产",
						init:init,
						initAfter:g_dialog.isHideTr,
						saveclick:save_click,
						autoHeight: true
					}
				);

				function init(el){
					g_grid.interceptData = function(data){
						for(var j=0;data&&j<data.length;j++){
							for(var i=0;i<nodeIds.length;i++){
								if(nodeIds[i] == data[j].edId){
									data.remove(j);
									j=j-1;
									break;
								}
							}
						}
					}
					g_grid.render(el.find("#table_div1"),{
						header:index_list_col_header,
						url:"asset/queryAsset",
						paramObj : saveObj,
						hideSearch : true,
						isLoad : true,
						tdClick : true
					});
				}
				function save_click(el,saveObj){
					//找出选中的对象
					if(g_grid.getData(el,{chk:true}).length==0){
						g_dialog.operateAlert(el,'请选择要添加的资产','error')
						return false;
					}
					var datas = g_grid.getData(el,{chk:true});
					var scene = nodeFunction.getNodeEntry().scene;
					for(var i=0;datas&&i<datas.length;i++){
						var item = customItem(datas[i],i,scene);
			    		var node = new CustomNode(item);
			    		node.type = "netNode";
			    		nodeFunction.getNodeEvent().addEventForNode(node);
			    		scene.add(node);
					}
					g_dialog.hide(el);
				}
			}
		});
	}
	
	function createCustomNode(obj){
	}
	function createInnerTopo(obj){
		$.ajax({
			type : "GET",
			url : "module/monitor_config/topo_manage_detail_tpl.html",
			success : function (data){
				g_dialog.dialog(
					$(data).find("[id=inner_topo_div]"),
					{
						width:"580px",
						title:"导入拓扑",
						init:init,
						saveclick:save_click
					}
				);
				function init(el){
					um_ajax_get({
						url : 'topoManage/getTopoList',
						successCallBack : function (data){
							data = data.map(function (item,index,array){
								item.text = item.topoName;
								item.id = item.topoId;
								return item;
							})
							el.find('[data-id=inner_topo]').select2({
								width:'100%',
								data : data
							}).toggle('change');
						}
					})
				}
				function save_click(el,saveObj){
					var topoId = el.find('[data-id=inner_topo]').val();
					um_ajax_get({
						url : 'topoManage/getTopo?topoId='+topoId,
						dataType:"html",
						successCallBack : function (data){
							var position = obj.position;
							var jsonobj = json2xml2.xml_str2json(data).root;
							if(jsonobj){
								_root = jsonobj;
								var scene = nodeFunction.getNodeEntry().scene;
								var translateX = _root._x;
								var translateY = _root._y;

								var minx = 10000;
								var miny = 10000;
								
								if(_root.nodes && _root.nodes.node){	
									_root.nodes.node = nodeFunction.objToArray(_root.nodes.node);
									for(var i=0;i<_root.nodes.node.length;i++){
										var item = _root.nodes.node[i];
										if(Number(item._x)<minx){
											minx = Number(item._x)
										}
										if(Number(item._y)<miny){
											miny = Number(item._y)
										}
									}
								}
								if(_root.nephograms && _root.nephograms.nephogram){	
									_root.nephograms.nephogram = nodeFunction.objToArray(_root.nephograms.nephogram);
									for(var i=0;i<_root.nephograms.nephogram.length;i++){
										var item = _root.nephograms.nephogram[i];
										if(Number(item._x)<minx){
											minx = Number(item._x)
										}
										if(Number(item._y)<miny){
											miny = Number(item._y)
										}
									}
								}
								if(_root.dynTexts && _root.dynTexts.dynText){
									_root.dynTexts.dynText = nodeFunction.objToArray(_root.dynTexts.dynText);
									for(var i=0;i<_root.dynTexts.dynText.length;i++){
										var item = _root.dynTexts.dynText[i];
										if(Number(item._x)<minx){
											minx = Number(item._x)
										}
										if(Number(item._y)<miny){
											miny = Number(item._y)
										}
									}
								}

								if(_root.nodes && _root.nodes.node){	
									_root.nodes.node = nodeFunction.objToArray(_root.nodes.node);
									for(var i=0;i<_root.nodes.node.length;i++){
										var item = _root.nodes.node[i];
										item._x = Number(item._x) - minx + Number(position.x) - scene.translateX;
										item._y = Number(item._y) - miny + Number(position.y) - scene.translateY;
										var node = new CustomNode(item);
										node.type = "netNode";
										nodeFunction.getNodeEvent().addEventForNode(node);
										scene.add(node);
									}
								}

								if(_root.lines && _root.lines.line){
									_root.lines.line = nodeFunction.objToArray(_root.lines.line);
									for(var i=0;i<_root.lines.line.length;i++)
									{
										var dependence = _root.lines.line[i];
										if(dependence._id.split("::").length >= 3){
											dependence.id = dependence._id;
										}
										else{
											dependence.id = dependence.networkLink.startId+"::"+dependence.networkLink.endId+"::"+lineNumber;
											dependence._id = dependence.id;
										}
										lineNumber = lineNumber+1;

										dependence._startId = dependence.networkLink.startId;
										dependence._endId = dependence.networkLink.endId;
										var link = null;
										try{
											if(dependence._type === "line"){
												link = new CustomLink(dependence,scene);
											}else if(dependence._type === "foldline"){
												link = new CustomFoldLink(dependence,scene);
											}else if(dependence._type === "squarelyflexionalline"){
												link = new CustomFlexionalLink(dependence,scene);
											}else {
												link = new CustomLink(dependence,scene);
											}
										}catch(e){
											continue;
										}

										link.id = dependence.id;
										link.type = "dependence";
										try{
											var startNode = nodeFunction.findNodeByScene(scene,dependence.networkLink.startId);
											nodeFunction.putModifyStyle(startNode,{
												lineColor:dependence.extend.strokeColor,
												lineSize:dependence.extend.lineWidth,
												lineAlpha:dependence.extend.alpha,
												endId:dependence.networkLink.endId},true);
										}catch(e){
										}
										nodeFunction.getNodeEvent().linkDbClick(link);
										scene.add(link);
									}
								}
								if(_root.nephograms && _root.nephograms.nephogram){	
									_root.nephograms.nephogram = nodeFunction.objToArray(_root.nephograms.nephogram);
									for(var i=0;i<_root.nephograms.nephogram.length;i++){
										var item = _root.nephograms.nephogram[i];
										item._x = Number(item._x) - minx + Number(position.x) - scene.translateX;;
										item._y = Number(item._y) - miny + Number(position.y) - scene.translateY;;
										customNephogramPublic.formatCloudByCloudObj(scene,item);
										nodeFunction.getNodeEntry().cloudNumber = nodeFunction.getNodeEntry().cloudNumber+1;
									}
								}
								if(_root.dynTexts && _root.dynTexts.dynText){
									_root.dynTexts.dynText = nodeFunction.objToArray(_root.dynTexts.dynText);
									for(var i=0;i<_root.dynTexts.dynText.length;i++){
										var item = _root.dynTexts.dynText[i];
										item._x = Number(item._x) - minx + Number(position.x) - scene.translateX;;
										item._y = Number(item._y) - miny + Number(position.y) - scene.translateY;;
										var textNode = new CustomTextNode(item);
										textNode.type = "text";
										scene.add(textNode);
										nodeFunction.getNodeEvent().addEventForNode(textNode);
									}
								}
								if(_root.squareBoxes && _root.squareBoxes.container){
									var container =  nodeFactory._group.appendAllNodeToContainer(scene,nodeFactory._group.getContainerArray(_root.squareBoxes.container));
								}
							}else {
								g_dialog.operateAlert(null,"数据加载出错","error");
							}
						}
					})
					g_dialog.hide(el);
				}
			}
		});
	}
	//初始事件,必须在initPanelData之前执行
//	for(var i=0;i<toolsLable.nettopo.length;i++){
//		nodeFactory.customComEvent(
//		{
//			type:toolsLable.nettopo[i][1],
//			node:{mouseup:nodeRightClick}//
//		});
//	}
	nodeFactory.customComEvent({
		type : 'inner_topo',
		dragend : createInnerTopo
	});
	nodeFactory.customComEvent(
			{
				type:"text",
				dblclick:function(){
				},		//针对工具栏组件
				mouseup: createTextNode,
				click:function(){},
				node:{mouseup:nodeRightClick,dbclick:nodeRightClick}//定义箭头事件处理函数
			});
	nodeFactory.customComEvent(
			{
				type:"netNode",
				node:{mouseup:nodeRightClick,leftmouseup:doLeftmouseup,dbclick:function(){}}//
			});
	nodeFactory.customComEvent(
			{
				type:"cloudNode",
				node:{mouseup:nodeRightClick,leftmouseup:doLeftmouseup,dbclick:function(){}}//
			});
	
	nodeFactory.customComEvent(
			{
				type:"addNode",
				mouseup:createAssetNode,
				click:function(){},
				dblclick:function(){},		//
			});
//	nodeFactory.customComEvent(
//			{
//				type:"topoInfo",
//				dblclick:getTopoInfo,		//
//			});
	nodeFactory.customComEvent(
			{
				type:"addLink",
				dblclick:function(){
					
				},
				mouseup:createLink,		//
			});
	nodeFactory.customComEvent(
			{
				type:appSystem,
				dblclick:createAppSystem,		//
				node:{mouseup:nodeRightClick,leftmouseup:doLeftmouseup}//
			});
	
	function initData(){
		if(nodeFunction.addAppStatus() == false){
			var param = new Object();
			param.topoId = appId;
			param.mainId = appId;
			nodeFunction.initPanelData(param);
		}
	}
	initData();

	function doLeftmouseup(obj){
		try{
			var nodeFunction = obj.nodeFactory._nodeFunction;
			var scene = nodeFunction.getNodeEntry().scene;
			if(nodeFunction.getNodeEntry().linkNode == true)
			{
				if(obj.node.type == "cloudNode"){
					g_dialog.operateAlert(null,"连线节点不可选择云节点，请重新选择！","error");
					return;
				}
				if(nodeFunction.getNodeEntry().linkStart == undefined){
					nodeFunction.getNodeEntry().linkStart = obj.node;
					g_dialog.operateAlert(null,"已选中起点，请选择终点","");
				}
				else
				{
					var text = "确定创建 【"+nodeFunction.getNodeEntry().linkStart.name+"】 到【 "+obj.node.name+"】 的连接关系？";
					nodeFunction.getNodeEntry().linkEnd = obj.node;
					 if(nodeFunction.getNodeEntry().linkStart.id == nodeFunction.getNodeEntry().linkEnd.id){
						 nodeFunction.getNodeEntry().linkStart = undefined;
						 nodeFunction.getNodeEntry().linkEnd = undefined;
						 return ;
					 }
					um_ajax_get({
						server : index_web_app_name,
						url : 'module/monitor_config/topo_manage_detail_tpl.html',
						successCallBack : function (dataHtml){
							g_dialog.dialog($(dataHtml).find('#link_type_info'),{
								width : '480px',
								title : text,
								init : function (el){
									el.find('[name=link_type]').click(function (){
										if($(this).val() == '1'){
											el.find('[name=fold_link_type]').prop('disabled',true);
											el.find('[name=fold_link_type]').removeAttr('checked');
										}else {
											el.find('[name=fold_link_type]').prop('disabled',false);
											el.find('[data-id=fold_link_type]').prop('checked',true);
										}
										if($(this).val() == '2'){
											el.find('#offsetGap_div').show();
										}else {
											el.find('#offsetGap_div').hide();
										}
									})
								},saveclick : function (el,saveObj){
									var dependence = {};
									dependence._id = nodeFunction.getNodeEntry().linkStart.id+"::"+nodeFunction.getNodeEntry().linkEnd.id+"::"+lineNumber;
									lineNumber = lineNumber + 1;
									 //进行检查是否已经连线
									 dependence.id = dependence._id;
									 dependence._startId = nodeFunction.getNodeEntry().linkStart.id;
									 dependence._endId = nodeFunction.getNodeEntry().linkEnd.id;
									 dependence.networkLink = {};
									 dependence.networkLink.startId = nodeFunction.getNodeEntry().linkStart.id;
									 dependence.networkLink.endId = nodeFunction.getNodeEntry().linkEnd.id;
									 var link ;
									 if(saveObj.link_type == '1'){
									 	link = 	new CustomLink(dependence,scene);
									 }else if(saveObj.link_type == '0'){
									 	link = 	new CustomFoldLink(dependence,scene);
									 	link.direction = saveObj.fold_link_type;
									 }else if(saveObj.link_type == '2'){
									 	link = 	new CustomFlexionalLink(dependence,scene);
									 	link.direction = saveObj.fold_link_type;
									 	link.offsetGap = Number(saveObj.offsetGap);
									 }
									 link.id = dependence.id;
									 link.type = "dependence";
									 scene.add(link);
									 nodeFunction.getNodeEvent().linkDbClick(link);
									 loadNetPorts({node:link});
									 if(
									 	nodeFunction.getNodeEntry().linkEnd.type == appSystem || 
									 	nodeFunction.getNodeEntry().linkStart == appSystem){
									 	link.isMylink = true;
									}
									nodeFunction.getNodeEntry().linkStart = undefined;
									nodeFunction.getNodeEntry().linkEnd = undefined;
									g_dialog.hide(el)
								},closeCbf : function (el){
									nodeFunction.getNodeEntry().linkStart = undefined;
									nodeFunction.getNodeEntry().linkEnd = undefined;
									g_dialog.hide(el)
								}
							});
						}
					})
					// g_dialog.operateConfirm(text,{saveclick : function (){
					// 	 var dependence = {};
					// 	 dependence._id = nodeFunction.getNodeEntry().linkStart.id+"::"+nodeFunction.getNodeEntry().linkEnd.id+"::"+lineNumber;
					// 	 lineNumber = lineNumber + 1;
					// 	 //进行检查是否已经连线
					// 	 dependence.id = dependence._id;
					// 	 dependence._startId = nodeFunction.getNodeEntry().linkStart.id;
					// 	 dependence._endId = nodeFunction.getNodeEntry().linkEnd.id;
					// 	 dependence.networkLink = {};
					// 	 dependence.networkLink.startId = nodeFunction.getNodeEntry().linkStart.id;
					// 	 dependence.networkLink.endId = nodeFunction.getNodeEntry().linkEnd.id;
					// 	 var link = new CustomLink(dependence,scene);
					// 	 link.id = dependence.id;
					// 	 link.type = "dependence";
					// 	 scene.add(link);
					// 	 nodeFunction.getNodeEvent().linkDbClick(link);
					// 	 loadNetPorts({node:link});
					// 	 if(
					// 	 	nodeFunction.getNodeEntry().linkEnd.type == appSystem || 
					// 	 	nodeFunction.getNodeEntry().linkStart == appSystem){
					// 	 	link.isMylink = true;
					// 	}
					// 	 nodeFunction.getNodeEntry().linkStart = undefined;
					// 	 nodeFunction.getNodeEntry().linkEnd = undefined;
					// },closeCbf:function(){
					// 	 nodeFunction.getNodeEntry().linkStart = undefined;
					// 	 nodeFunction.getNodeEntry().linkEnd = undefined;
					// }});
				}
				return;
			}
		}catch(e){
			console.log(e);
		}
	}

	for(var i=0;i<toolsLable.nettopo.length;i++){

		var node = nodeFactory.node.createNode("canvasTool");
		node.id="node-"+i;
		node.name=toolsLable.nettopo[i][0];
		node.type=toolsLable.nettopo[i][1];
		node.compType=toolsLable.nettopo[i][1];
		node.bimg=toolsLable.nettopo[i][2];
		node.istool = true;
		node.beginId = toolsLable.nettopo[i][3];
		if(toolsLable.nettopo[i][4] != undefined)
			node.tiptext=toolsLable.nettopo[i][4];
		node.x = 2;
		node.y = 10+60*i;
		$("#canvasTool").append(node.newToolNode());
	}
	$(document).ready(function(){
		initEvent();
	});

		/**
		 * 修改事件
		 */
		//修改组事件，分组只有右键事件
		nodeFactory._group.customGroupEvent=function(obj){
			var event = obj.event;
			$("#link_menu").hide();
			$("#node_menu").hide();
			$("#container_menu").css({
				top: event.pageY,
				left: event.pageX
			}).show().focus().blur(function (){
				$(this).hide();
				currentObj = undefined;
			});
			currentObj = obj;
			$("#container_menu a").click(function (){
				var text = $(this).text();
				if(text == "更改属性"){
					containerInfo(currentObj);
				}else if(text == "增删节点"){
					containerDealNode(currentObj);
				}else if(text == "删除容器"){
					nodeFactory._group.id = currentObj.node.id;
					nodeFactory._group.removeGroup(nodeFunction.getScene(),currentObj.node.id);
					nodeFactory._group.id = undefined;
					currentObj = undefined;
				}
				$('#container_menu').hide();
			});
		}
		function containerDealNode(obj){
			$.ajax({
				type : "GET",
				url : "module/monitor_config/app_monitor_config_detail_group.html",
				success : function (data){
					g_dialog.dialog(
						$(data).find("[id=addnodeForGroup]"),
						{
							width:"580px",
							title:"分组操作",
							init:init,
							saveclick:save_click
						}
					);

					function init(el){
						nodeFactory._group.closeEl = el;

						//已在组内的
						var innodes = obj.node.childs;
						innodes = innodes.map(function (item){
							return {
								value : item.id,
								text : item.name
							}
						})
						//不在组内的
						var outnodes =nodeFactory._group.findOutContainerNode(nodeFunction.getScene());
						outnodes = outnodes.map(function (item){
							return {
								value : item.id,
								text : item.name
							}
						})
						abPanel.render(el.find(".centent") ,{
							left_data:outnodes,
							right_data:innodes
						});
					}
					function save_click(el,saveObj){
						var dataArray = abPanel.getValue(el.find(".centent"));

						obj.node.removeAll();
						for(var i=0;i<dataArray.length;i++){
							var nodes = new Array();
							nodes[0] = nodeFunction.findNodeByScene(nodeFunction.getScene(),dataArray[i]);
							nodeFactory._group.addNodeForGroup(obj.node,nodes);
						}

						// resetColor("isGroup");
						// resetColor("isFont");
						nodeFactory._group.modifyGroupStlye();
						g_dialog.hide(el);
					}
				}
			});
		}
		function containerInfo(obj){
			$.ajax({
				type : "GET",
				url : "module/monitor_config/app_monitor_config_detail_group.html",
				success : function (data){
					g_dialog.dialog(
						$(data).find("[id=modifygroup]"),
						{
							width:"580px",
							title:"分组操作",
							init:init,
							saveclick:save_click,
							autoHeight: true
						}
					);

					function init(el){
						nodeFactory._group.closeEl = el;
						$(el).find("#modifyGroupStlye_remove").click(function(){
							nodeFactory._group.removeGroup(nodeFunction.getScene());
						});
						nodeFactory._group.fillAttrs(obj.node);
						(obj.node.borderWidth || obj.node.borderWidth == 0) && $(el).find('[data-id=borderWidth]').val(obj.node.borderWidth);
						(obj.node.dashedPattern || obj.node.dashedPattern == 0) && $(el).find('[data-id=dashedPattern]').val(obj.node.dashedPattern);
						(obj.node.borderRadius || obj.node.borderRadius == 0) && $(el).find('[data-id=borderRadius]').val(obj.node.borderRadius);
						var hex = ("RGB("+obj.node.fillColor+")").colorHex();
						var hex1 = ("RGB("+obj.node.borderColor+")").colorHex();
						$(el).find("#groupcoloriframe").attr("src",nodeFunction.getNodeEntry().colorStagePath+"?color="+hex);
						$(el).find("#groupbordercoloriframe").attr("src",nodeFunction.getNodeEntry().colorStagePath+"?color="+hex1);
					}
					function save_click(el,saveObj){
						resetColor("isGroup");
						resetColor("isFont");
						resetColor("border");
						nodeFactory._group.modifyGroupStlye();
						g_dialog.hide(el);
					}
				}
			});
		}
		var currentObj;
		nodeFunction.getStage().click(function(event){
			if(event.button == 0)
				$("#node_menu").hide();
			$("#link_menu").hide();
			$("#container_menu").hide();
			currentObj = undefined;
		});
		function nodeRightClick(obj){
			var event = obj.event;
			$("#link_menu").hide();
			$("#container_menu").hide();
			$("#node_menu").css({
				top: event.pageY,
				left: event.pageX-80
			}).show().focus().blur(function (){
				$(this).hide();
				currentObj = undefined;
			});
			if(obj.node.type == "text")
			{
				$("#node_menu").find("#reset").hide();
				$("#node_menu").find("#textnode").show();
			}
			else
			{
				$("#node_menu").find("#monitor").show();
				//alert(obj.node.type);
				if(obj.node.type != "cloudNode"){
					$("#node_menu").find("#textnode").hide();
					var cloud = customNephogramPublic.getCloud(obj.node)
					if(cloud != null){
						$("#node_menu").find("#reset").show();
						$("#node_menu a").attr("value",cloud.id);
					}
					else
						$("#node_menu").find("#reset").hide();
				}
				else{
					$("#node_menu").find("#textnode").show();
					$("#node_menu").find("#reset").hide();
				}
			}
			currentObj = obj;
		}
		function linkRightClick(obj){
			var event = obj.event;
			$("#node_menu").hide();
			$("#container_menu").hide();
			$("#link_menu").css({
				top: event.pageY,
				left: event.pageX
			}).show().focus().blur(function (){
				$(this).hide();
				currentObj = undefined;
			});
			currentObj = obj;
		}
		$("#node_menu a").click(function (event){
			var text = $(this).text();
			if(text == "更改属性"){
				currentObj.displayId = "diplay_attrs";
				currentObj.hiddenId = "diplay_monitorList";
				currentObj.umIsUpdate=true;
				if(currentObj.node.type == "text"){
					createTextNode(currentObj);
				}
				else if(nodeFunction.isCustomNode(currentObj.node) == true)
				{
					createCustomNode(currentObj);
				}
				else if(currentObj.node.type == "cloudNode")
				{
					createcloud(currentObj.node._nodes,currentObj.node);
				}
				else
					dealRightClickForNode(currentObj,"属性修改");
			}else if(text == "绑定/解除监控器"){
				currentObj.displayId = "diplay_monitorList";
				currentObj.hiddenId = "diplay_attrs";
				dealRightClickForNode(currentObj,"绑定/解除监控器");
			}else if(text == "删除节点"){
				var localCuttrntObj = $.extend({},currentObj);
				var str = "确认删除该节点?";
				if(localCuttrntObj.node.type == "cloudNode")
					str = "确认删除云节点？";
				g_dialog.operateConfirm(str,{
					title : "确认删除",
					saveclick : deleteNode
				});
				function deleteNode(){
					if(localCuttrntObj.node.type != "cloudNode"){
						var nodeEntry = nodeFunction.getNodeEntry();
						nodeFunction.deleteNodeByScene(nodeEntry.scene,localCuttrntObj.node);
					}else{
						
						customNephogramPublic.removeCloud(nodeFunction.getScene(),localCuttrntObj.node);
					}

					currentObj = undefined;
				}
			}
			else if(text == "恢复云图"){
				var node = customNephogramPublic.popCloud($(this).attr("value"));
				customNephogramPublic.formatCloud(nodeFunction.getScene(),node._nodes,node);
			}
			$('#node_menu').hide();
		});
		$("#link_menu a").click(function (event){
			var text = $(this).text();
			if(text == "更改属性"){
				dealRightClickForLine(currentObj);
			}
			else if(text == "端口配置"){
				loadNetPorts(currentObj);
			}
			else if(text == "删除连线"){
				var localCuttrntObj = $.extend({},currentObj);
				g_dialog.operateConfirm("确认删除该连线?",{
					title : "确认删除",
					saveclick : deleteNode
				});
				function deleteNode(){
					var nodeEntry = nodeFunction.getNodeEntry();
					nodeFunction.deleteNodeByScene(nodeEntry.scene,localCuttrntObj.node);
					currentObj = undefined;
				}
			}

			$("#link_menu").hide();
		});
		function dealRightClickForNode(obj,text){

		}
		function dealRightClickForLine(obj){
			$.ajax({
				type : "GET",
				url : "module/monitor_config/app_monitor_config_detail_line.html",
				success : function (data){
					g_dialog.dialog(
						$(data).find("[id=modifyline]"),
						{
							width:"580px",
							title:"线段属性修改",
							init:init,
							saveclick:save_click
						}
					);

					function init(el){
						var scene = nodeFunction.getNodeEntry().scene;
						var lines = scene.selectedElements;
						for(var i=0;i<lines.length;i++){
							var item = lines[i];
							if(item.elementType != 'link'){
								g_dialog.hide(el);
								g_dialog.operateAlert(null,"该操作选取组件中只能有连线",'error');
								return ;
							}
						}
						var line = lines[0];
						//此处不需要修改线段名称功能
						// if(nodeFunction.checkHasTempType(obj.node,appSystem) == false)
							$(el).find("input[name='lineText']").parent().parent().hide();
						// $(el).find("#pidLine").val(obj.node.id);
						$(el).find("#canvasDrawShowAttrLine_distance").blur(function(){
							nodeFunction.updateLineDistance();
						});
						$(el).find("#canvasDrawShowAttrLine_doMod").mouseup(function(){
							//
							if($(this).attr("clicktimes") == undefined )
								$(this).attr("clicktimes","checked");
							else
								$(this).removeAttr("clicktimes");
						});
						
						
						$(el).find(".lineBack").hover(function(){
							if($(this).attr("isClick") != undefined)
								return;
							$(this).css("background-color","rgba(180,180,180,0.5)");
						},function(){
							if($(this).attr("isClick") != undefined)
								return;
							$(this).css("background-color","");
						});
						var divs = $(el).find("div[id^=lineSize]");
						for(var i=0;i<divs.length;i++){
							$(divs[i]).click(function(){
								$(this).siblings().css("background-color","");
								$(this).siblings().css("border","");
								$(this).siblings().css("border-color","");
								$(this).siblings().removeAttr("isClick");
								$(this).css("background-color","rgba(221,126,107,0.6)");
								$(this).attr("isClick",true);
								//border: 1px;border-color: red;
								$(this).css("border","1px");
								$(this).css("border-color","red");
								//
								$("#canvasDrawShowAttrLine").find("input[name='size']").val($(this).attr("value"));
							});
						}
						///js/lib/colorStage.html?color=obj.node.strokeColor
						// setColor(obj.node.strokeColor);
						var hex = ("RGB("+line.strokeColor+")").colorHex();
						$(el).find("#coloriframe").attr("src",nodeFunction.getNodeEntry().colorStagePath+"?color="+hex);
						nodeFunction.getNodeEntry().closeEl = el;
						nodeFunction.initDeleteLineButton(nodeFunction.getNodeEntry().canDrawShowAttr,el);
						nodeFunction.getNodeEvent().dealClickAndDblclick(obj.event,line);
						
						if(checkIsNULL(line.attributes) == true){
							$(el).find("#pLine_dependence").remove();
						}
					}
					function save_click(el,saveObj){
						resetColor();
						nodeFunction.updateLineAttr(el);
						g_dialog.hide(el);
					}
				}
			});
		}

		
		function createcloud(nodes,model){
			$.ajax({
				type : "GET",
				url : "module/monitor_config/topo_manage_detail_tpl.html",
				success : function (data){
					g_dialog.dialog(
						$(data).find("[id=createcloud]"),
						{
							width:"580px",
							title:"属性配置",
							init:init,
							saveclick:save_click
						}
					);
					function init(el){
						//新增
						if(model == undefined)
						{
							$(el).find(".editModel").remove();
							$(el).find("#cloudcolorImg").attr("src",index_web_app_name+"img/topo/new/cloud/cloud.svg");
						}
						else
						{
							$(el).find("#name").val(model.text);
							$(el).find("#cloudcolor").val(model.cloudcolor);
							$(el).find("#desc").val(model.desc);
							$(el).find('[data-id=width]').val(model.width);
							$(el).find('[data-id=height]').val(model.height);
							var color = model.cloudcolor;
							if(model.cloudcolor == "white")
								color = "";
							$(el).find("#cloudcolorImg").attr("src",index_web_app_name+"img/topo/new/cloud/"+color+"cloud.svg");
							
							
							//instage
							var scene = nodeFunction.getScene();
							var instage = $(el).find("#instage");
							var outstage = $(el).find("#outstage");
							
							var outNodes = scene.findElements(function (a){
				    			return a.type == "netNode";
				    		});
							for(var i=0;i<model._nodes.length;i++){
								var option = $('<option value="'+model._nodes[i].id+'">'+model._nodes[i].text+'</option>');
								instage.append(option);
							}
							for(var i=0;i<outNodes.length;i++){
								var option = $('<option value="'+outNodes[i].id+'">'+outNodes[i].text+'</option>');
								outstage.append(option);
							}
							!model.goTopo && (model.goTopo = "");
							$(el).find("#goTopo").val(model.goTopo);
							
							$.ajax({
								url : index_web_app + index_soc_prefix + 'topoManage/getTopoListForJump?1=1&topoId='+this_params.topoId,
								type : 'get',
								async : true,
								timeout : 6000,
								xhrFields: {
									withCredentials: true
								},
								success : function (data){
									var root = json2xml.xml2json(data).root;
									var topos = new Array();
									if(root.topo instanceof Array)
										topos = root.topo;
									else
										topos[0] = root.topo;
									for(var i=0;i<topos.length;i++){
										var selected = "";
										if(topos[i].id == model.goTopo){
											selected = 'selected="selected"';
										}
										$(el).find("#goTopo").append($('<option value="'+topos[i].id+'" '+selected+'>'+topos[i].name+'</option>'));
									}
								},
								error : function (e){
									console.log(e);
								}
							});
							
							$(el).find('#chevron-right').click(function(){
								var $options = $('option:selected', $("#outstage"));//注意此处“option”与“:”之间的空格，有空格是不可以的
								//进行挂载
								g_dialog.operateConfirm("添加节点到云？",{saveclick : function (){
									$options.appendTo('#instage');
								}});
							});
							$(el).find('#chevron-left').click(function(){
								var $options = $('option:selected', $("#instage"));
								g_dialog.operateConfirm("从云中移除节点？",{saveclick : function (){
									$options.appendTo('#outstage');
								}});
							});
							
						}
						
						$(el).find("#cloudcolor").change(function(){
							if($(this).val() == "white")
								$(el).find("#cloudcolorImg").attr("src",index_web_app_name+"img/topo/new/cloud/cloud.svg");
							else 
								$(el).find("#cloudcolorImg").attr("src",index_web_app_name+"img/topo/new/cloud/"+$(this).val()+"cloud.svg");
						});
							
					}
					function save_click(el,saveObj){
						var scene = nodeFunction.getScene();
						//创建云
						if(checkIsNULL(saveObj.name) == false)
						{
							//新增
							if(model == undefined){
								while(true){
									var no = nodeFunction.findNodeByScene(scene,"cloud"+nodeFunction.getNodeEntry().cloudNumber);
									if(no == null || no == undefined){
										break;
									}
									console.log(" ------------- "+nodeFunction.getNodeEntry().cloudNumber);
									nodeFunction.getNodeEntry().cloudNumber = nodeFunction.getNodeEntry().cloudNumber+1;
								}
								saveObj.id = "cloud"+nodeFunction.getNodeEntry().cloudNumber;
								nodeFunction.getNodeEntry().cloudNumber = nodeFunction.getNodeEntry().cloudNumber+1;
//								cloudNumber = cloudNumber +1;
								customNephogramPublic.formatCloud(scene,nodes,saveObj);
							}
							//修改
							else
							{
								var options = $(el).find("#instage option");
								if(options && options.length > 0){
									//删除云
									customNephogramPublic.removeCloud(scene,model);
									saveObj.x = model.x;
									saveObj.y = model.y;
									saveObj.id = model.id;
									//创建云
									var _nodes = new Array();
									for(var i = 0;i<options.length;i++){
										_nodes[_nodes.length] = nodeFunction.findNodeByScene(scene,$(options[i]).val());
									}
									customNephogramPublic.formatCloud(scene,_nodes,saveObj);
								}
								else{
									g_dialog.operateAlert(null,"节点不能空！","error");
								}

							}

						}
						else{
							g_dialog.operateAlert(null,"节点名称不能为空！","error");
						}
						
						g_dialog.hide(el);
					}
				}
			});
			
		}
		
	
		function initBgi(){
			var defaultBackgroundURL = index_web_app_name + 'img/topo/backimg.png';
			nodeFunction.getNodeEntry().scene.background = defaultBackgroundURL;
			nodeFunction.getNodeEntry().scene.backgroundRepeat = 'repeat';
			$.ajax({
				url : index_web_app + index_soc_prefix + 'topoManage/getTopoInfo',
				data : {topoId:this_params.topoId,regionId:this_params.regionId},
				type : 'post',
				dataType : 'json',
				async : true,
				timeout : 6000,
				xhrFields: {
					withCredentials: true
				},
				success : function (data){
					data.topoName && (document.title = data.topoName);
					data.topoName && $("#titlename").text(data.topoName);
					var bgi = data.topoBackground;
					!!bgi && setBackgroundImage(bgi);
				},
				error : function (e)
				{
				}
			});

			function setBackgroundImage(url){
				var bgiurl = url.split(',')[0];
				if(!bgiurl){
					nodeFunction.getNodeEntry().scene.background = defaultBackgroundURL;
					nodeFunction.getNodeEntry().scene.backgroundRepeat = 'repeat';
				}else {
					var bgis = url.split(',');
					um_ajax_get({
						url : 'topoManage/getImageBase64',
						paramObj : {imgUri : bgis[0]},
						successCallBack : function (data){
							var img = new Image();
							img.src = data;
							nodeFunction.getNodeEntry().scene.background = img;
							if(bgis.length==2){
								nodeFunction.getNodeEntry().scene.backgroundRepeat = bgis[1];
							}else {
								nodeFunction.getNodeEntry().scene.backgroundRepeat = undefined;
							}
						},
						failCallBack : function (){
							nodeFunction.getNodeEntry().scene.background = defaultBackgroundURL;
							nodeFunction.getNodeEntry().scene.backgroundRepeat = 'repeat';
						}
					})
				}
			}
		}
});
});